package com.qgs.rabbitmqapi.confirm;

import com.rabbitmq.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @Author: 蔡翔
 * @Date: 2019/7/19 9:03
 * @Version 1.0
 */
public class Consumer {
    public static void main(String[] args) throws Exception {
        Logger logger = LoggerFactory.getLogger(Consumer.class);
        //1.创建一个ConnectionFactory,并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.0.229"); //直接填地址不要 http://192.168.0.229
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        //2.获取Connection
        Connection connection = connectionFactory.newConnection();

        //3.通过一个Connection创建一个新的channel
        Channel channel = connection.createChannel();

        String exchangeName = "test_confirms_exchange";
        String routringKey = "confirm.save";  //“confirm.#” ，“confirm.*” 都是可以的，匹配规则一般可以是写在消费端的。
        String queueName = "test_confirm_queue";

        //声明路由器和交换机 在consumer 和 producer端都是可以的。
        //声明交换机和队列
        channel.exchangeDeclare(exchangeName,"topic",false,false,false,null);
        channel.queueDeclare(queueName,false,false,true,null);
        //然后进行绑定设置。
        channel.queueBind(queueName,exchangeName,routringKey);

        //5.创建消费者
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            @Override   //这里DefaultConsumer 有一个好处就是会自动监听队列的里面的所有数据而不是 nextDelivery()
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                String messgae = new String(body,"UTF-8");
                logger.info("客户端接收到的数据是："+messgae);

            }
        };


        //6.设置channel
        //basicConsume(String queue, boolean autoAck, Consumer callback);ack是当客户端取到一条message后会回送给broker一条信息表明收到，
        // autoAck表明自动签收；callback 就是具体的消费者对象了
        channel.basicConsume(queueName,true,defaultConsumer);

    }
}
